package com.example.classrecord;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataHandler {
	public static final String NAME = "name";
	public static final String NUMBER = "number";
	public static final String STUDENT = "student";
	public static final String TABLE_NAME = "classTable";
	public static final String DATA_BASE_NAME = "classDataBase";
	public static final int DATABASE_VERSION = 1;
	public static final String TABLE_CREATE = "create table classTable (name text not null, number not null, student not null);";

	DataBaseHelper dbHelper;
	Context ctx;
	SQLiteDatabase db;
	
	public DataHandler(Context ctx){
		this.ctx = ctx;
		dbHelper = new DataBaseHelper(ctx);
	}
	
	private static class DataBaseHelper extends SQLiteOpenHelper{

		public DataBaseHelper(Context ctx){
			super(ctx,DATA_BASE_NAME,null,DATABASE_VERSION);
		}
		
		@Override
		public void onCreate(SQLiteDatabase db) {
			try{
				db.execSQL(TABLE_CREATE);
			}
			catch(Exception e){
				e.printStackTrace();
			}
		}
		
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub
			db.execSQL("DROP TABLE IF EXISTS classTable");
			onCreate(db);
		}
		
	}
	
	/** Opens the database **/
	public DataHandler open(){
		db = dbHelper.getWritableDatabase();
		return this;
	}
	
	/** Closes the database **/
	public void close(){
		dbHelper.close();
	}
	
	/** Inserts data into database **/
	public long insertData(String name, String number, String student){
		ContentValues content = new ContentValues();
		content.put(NAME, name);
		content.put(NUMBER, number);
		content.put(STUDENT, student);
		return db.insertOrThrow(TABLE_NAME, null, content);
	}
	
	/** Delete data from database **/
	public void delete(String n){
		db.delete(TABLE_NAME, null, null);
		//db.rawQuery("DELETE FROM " + TABLE_NAME + " WHERE " + NAME + " = " + "\"" + n + "\"", null);
	}
	
	/** Returns data from database **/
	public Cursor returnData(){
		return db.query(TABLE_NAME, new String[] {NAME,NUMBER,STUDENT}, null, null, null, null, null);
	}
}
